<script setup lang="ts">
import axios from "@/axios";
import { ElMessage } from "element-plus";
import { ref } from "vue";

const visible = ref(false);
const isEditor = ref(false);
class UserForm {
  id = undefined;
  username = "";
  password = "";
}

let userForm = ref(new UserForm());

const emit = defineEmits(["update"]);

const open = (data: any) => {
  visible.value = true;
  if (data) {
    isEditor.value = true;
    userForm.value = data;
  } else {
    isEditor.value = false;
    userForm.value = new UserForm();
  }
};

const handleCancel = () => {
  userForm.value = new UserForm();
  visible.value = false;
};

const beforeClose = (deno: any) => {
  handleCancel();
  deno();
};

// 提交表单
const submitForm = async () => {
  console.log(userForm.value);
  
  const ret = await axios.post("/user/create", userForm.value);
  if (ret.status === 201) {
    emit("update");
    handleCancel();
    ElMessage.success("添加成功");
  } else {
    console.log(ret);
    // const { message } = ret.response
    // ElMessage.error(message);
  }
};

const updateUser = async () => {
  const ret = await axios.post("/user/update", userForm);
  if (ret.status === 201) {
    ElMessage.success("修改成功");
    userForm;
    emit("update");
    handleCancel();
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    :before-close="beforeClose"
    v-model="visible"
    title="用户角色"
    :with-header="false"
  >
    <el-form
      ref="userFormRef"
      label-position="left"
      label-width="auto"
      :model="userForm"
      style="max-width: 600px"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model="userForm.username"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="userForm.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer v-slot="scope">
      <div class="drawer-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button v-if="!isEditor" type="primary" @click="submitForm"
          >添加</el-button
        >
        <el-button v-else type="primary" @click="updateUser">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped lang="less"></style>
